var Hogan = require('hogan.js');


//util js
var Hogan = require('hogan.js');
var config = {
    serverHost: 'http://localhost:8080/'
}


var _util = {
    //异步请求
    request: function (param) {
        var _this = this;
        $.ajax({
            type: param.method || 'GET',
            url: param.url || '',
            dataType: param.type || 'json',
            data: param.data || '',
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },

            success: function (res) {
                if (0 === res.status) {
                    typeof param.success === 'function' && param.success(res.data, res.message);
                }
                else if (10 === res.status) {//未登录情况
                    _this.doLogin();

                }
                else if (1 === res.status) {
                    typeof param.error === 'function' && param.error(res.message);
                }

            },

            error: function (errMsg) {
                typeof param.error === 'function' && param.error('服务器异常');

            }
        });
    },
    doLogin: function () {
        if (confirm("您没有登录需要登录")) {

            window.location.href = './account-login.html?redirect=' + encodeURIComponent(window.location.href);

        }

    },
    //url连接localhost:....
    getServerURL: function (path) {
        return config.serverHost + path;
    },
    validateField: function (fieldType, fieldValue) {
        var fieldValue = $.trim(fieldValue);
        if (fieldType === 'require') {
            return !!fieldValue;
        }
        else if (fieldType === 'phone') {
            var strTemp = /^[1][3-9][\d]{9}/;
            if (strTemp.test(fieldValue)) {
                return true;
            } else {
                alert('手机号不合法!');
                return false;
            }
        }
    },

    getURLparam: function (name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        var result = window.location.search.substring(1).match(reg);
        return result ? decodeURIComponent(result[2]) : null;
    },
    renderHtml: function (htmlTemplate, data) {
        var hoganTemplate = Hogan.compile(htmlTemplate);
        var result = hoganTemplate.render(data);
        // console.log('result:' + result);
        return result;

    }


};


module.exports = _util;